const Proxy = require('../../proxy')
const webDataUtil = require('../../util/webDataUtil')
const axios = require('axios')

const BtbIndex = Proxy.BtbIndex

function getAstItem (list, code) {
  for (let i = 0; i < list.length; i++) {
    if (list[i].symbol === `${code}USDT`) {
      return list[i]
    }
  }
  return false
}

// 获取合约账户财务信息
module.exports = async function () {
  const balanceRes = await webDataUtil.binance('getFuturesAccount')
  const myBalance = balanceRes.data || {}
  const hl = await axios({
    method: 'get',
    url: `https://push2.eastmoney.com/api/qt/stock/get?secid=133.USDCNH&ut=f057cbcbce2a86e2866ab8877db1d059&forcect=1&fields=f43&invt=2&cb=jQuery18302206528858403829_1652938694805&wbp2u=|0|0|0|wap&_=1652938775453`
  }).then((data) => {
    let str = data.data.slice(data.data.indexOf('(') + 1, data.data.lastIndexOf(')'))
    let list = JSON.parse(str).data
    return list['f43'] || 0
  })
  const positionsList = myBalance.positions || []
  let btbRes = await BtbIndex.findWidthField({
    status: 1,
    hy_status: 1
  }, { code: 1 }, {
    sort: '-proportion'
  })
  let map = {}
  let totalNotional = 0
  btbRes.forEach((v, index) => {
    const astItem = getAstItem(positionsList, v.code)
    // 很小
    if (Math.abs(parseFloat(astItem.notional)) < 1) {
      astItem.notional = 0
      astItem.unrealizedProfit = 0
      astItem.initialMargin = 0
    }
    // 取绝对值
    totalNotional += Math.abs(parseFloat(astItem.notional))
    map[v.code] = {
      // 入场价
      entryPrice: parseFloat(astItem.entryPrice),
      // 份额，可正可负
      positionAmt: parseFloat(astItem.positionAmt),
      // 持仓市值，可正可负
      notional: parseFloat(astItem.notional),
      // 收益
      unrealizedProfit: parseFloat(astItem.unrealizedProfit),
      // 保证金，正数
      initialMargin: parseFloat(astItem.initialMargin),
      // 杠杆
      leverage: parseFloat(astItem.leverage)
    }
  })
  return {
    // 汇率
    hl: parseFloat(hl) / 10000,
    // 总资产
    balance: parseFloat(myBalance.totalMarginBalance),
    // 总保证金，正数
    totalInitialMargin: parseFloat(myBalance.totalInitialMargin),
    // 总收益
    totalUnrealizedProfit: parseFloat(myBalance.totalUnrealizedProfit),
    // 剩余可用，正数
    availableBalance: parseFloat(myBalance.availableBalance),
    // 总持仓，正数
    totalNotional: totalNotional,
    indexMap: map
  }
}
